package com.mengpeng.toastxutils;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.Shape;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.*;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.lang.reflect.Method;

public class ToastXUtils {
    @SuppressLint("StaticFieldLeak")
    private static PopupWindow window;
    private static ToastXOnClickListener mListener;
    @SuppressLint("HandlerLeak")
    private static Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                if (window != null && window.isShowing()) {
                    window.dismiss();
                }
            }
        }
    };

    public interface ToastXOnClickListener {
        void onClick();
    }

    public static void show(Activity activity, String message, String btnText) {
        show(activity, message, btnText, GravityType.LEFT, 85, 1500, null);
    }

    public static void show(Activity activity, String message, String btnText, ToastXOnClickListener listener) {
        show(activity, message, btnText, GravityType.RIGHT, 85, 4000, listener);
    }


    private static void show(Activity activity, String message, String btnText, GravityType type, int percent, final long dur, ToastXOnClickListener listener) {
        mListener = listener;
        handler.removeMessages(1);

        View view;
        if (type == GravityType.LEFT) {
            view = LayoutInflater.from(activity).inflate(R.layout.layout_toastx_left, null);
        } else {
            view = LayoutInflater.from(activity).inflate(R.layout.layout_toastx_right, null);
        }
        RelativeLayout toastx_container = view.findViewById(R.id.toastx_container);
        TextView toastx_content = view.findViewById(R.id.toastx_content);
        TextView toastx_btn = view.findViewById(R.id.toastx_btn);

        GradientDrawable background = (GradientDrawable) toastx_container.getBackground();
        background.setColor(Color.parseColor("#33ff0000"));
        //toastx_container.setBackground(background);

        ShapeDrawable drawable = new ShapeDrawable();
        drawable.setShape(new Shape() {
            @Override
            public void draw(Canvas canvas, Paint paint) {
                float height = getHeight();
                float width = getWidth();
                paint.setAntiAlias(true);
                paint.setColor(Color.parseColor("#33ff00ff"));
                paint.setStyle(Paint.Style.FILL);

                RectF rectF = new RectF();
                rectF.left = 0;
                rectF.top = 0;
                rectF.right = (int) (width * 1.5);
                rectF.bottom = height;
                canvas.drawRoundRect(rectF, height / 2, height / 2, paint);
            }
        });
        toastx_container.setBackground(drawable);

        //信息内容
        if (!TextUtils.isEmpty(message)) {
            toastx_content.setText(message);
        }
        boolean focuable;
        //按钮字
        if (!TextUtils.isEmpty(btnText)) {
            toastx_btn.setText(btnText);
            toastx_btn.setVisibility(View.VISIBLE);
            focuable = listener != null;
        } else {
            focuable = false;
            toastx_btn.setVisibility(View.GONE);
        }

        if (window != null && window.isShowing()) {
            window.dismiss();
            window = null;
        }
        window = new PopupWindow(view,
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.WRAP_CONTENT,
                focuable);
        // 设置PopupWindow是否能响应外部点击事件
        window.setOutsideTouchable(focuable);
        // 设置PopupWindow是否能响应点击事件
        window.setTouchable(focuable);

        //此时获取的是真实的屏幕高度
        DisplayMetrics metrics = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getRealMetrics(metrics);
        int heightPixels = metrics.heightPixels;

        int statusBarHeight = getStatusBarHeight(activity);
        int navigationBarHeight = 0;
        if (hasNavBar(activity)) {
            navigationBarHeight = getNavigationBarHeight(activity);
        }
        int height = heightPixels - statusBarHeight - navigationBarHeight;

        if (percent >= 100) {
            percent = 100;
        } else if (percent <= 0) {
            percent = 0;
        }

        if (type == GravityType.LEFT) {
            window.setAnimationStyle(R.style.toastx_left_anim_style);
            window.showAtLocation(window.getContentView(), Gravity.NO_GRAVITY, 0, height * percent / 100);
        } else if (type == GravityType.RIGHT) {
            window.setAnimationStyle(R.style.toastx_right_anim_style);
            window.showAtLocation(window.getContentView(), Gravity.NO_GRAVITY, 0, height * percent / 100);
        } else {

        }

        //点击事件
        if (listener != null) {
            toastx_btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mListener != null && window != null) {
                        mListener.onClick();
                        if (window.isShowing()) {
                            window.dismiss();
                            handler.removeMessages(1);
                        }
                    }
                }
            });
        }

        window.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                handler.removeMessages(1);
            }
        });

        handler.sendEmptyMessageDelayed(1, dur);
    }

    public enum GravityType {
        LEFT, RIGHT
    }

    /**
     * 获取状态栏的高度
     */
    private static int getStatusBarHeight(Context context) {
        int result = 0;
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = context.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

    //获取虚拟按键的高度
    public static int getNavigationBarHeight(Context context) {
        int result = 0;
        if (hasNavBar(context)) {
            Resources res = context.getResources();
            int resourceId = res.getIdentifier("navigation_bar_height", "dimen", "android");
            if (resourceId > 0) {
                result = res.getDimensionPixelSize(resourceId);
            }
        }
        return result;
    }

    /**
     * 检查是否存在虚拟按键栏
     */
    @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    public static boolean hasNavBar(Context context) {
        Resources res = context.getResources();
        int resourceId = res.getIdentifier("config_showNavigationBar", "bool", "android");
        if (resourceId != 0) {
            boolean hasNav = res.getBoolean(resourceId);
            // check override flag
            String sNavBarOverride = getNavBarOverride();
            if ("1".equals(sNavBarOverride)) {
                hasNav = false;
            } else if ("0".equals(sNavBarOverride)) {
                hasNav = true;
            }
            return hasNav;
        } else { // fallback
            return !ViewConfiguration.get(context).hasPermanentMenuKey();
        }
    }

    /**
     * 判断虚拟按键栏是否重写
     */
    private static String getNavBarOverride() {
        String sNavBarOverride = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            try {
                Class c = Class.forName("android.os.SystemProperties");
                Method m = c.getDeclaredMethod("get", String.class);
                m.setAccessible(true);
                sNavBarOverride = (String) m.invoke(null, "qemu.hw.mainkeys");
            } catch (Throwable e) {
            }
        }
        return sNavBarOverride;
    }

}
